package example.telosys.persistence;

import org.demo.vo.bean.Employee;
import org.telosys.persistence.PersistenceManager;
import org.telosys.persistence.PersistenceManagerFactory;
import org.telosys.persistence.TelosysPersistence;

public class SampleTransaction {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		// 1) Get the factory for the default database (or for a specific database if multiple DB)
		PersistenceManagerFactory pmf = TelosysPersistence.getPersistenceManagerFactory() ;
		// PersistenceManagerFactory pmf = TelosysPersistence.getPersistenceManagerFactory(1) ; // DB #1
		
		// 2) Get a PersistenceManager
		PersistenceManager pm = pmf.createPersistenceManager() ;
		
		createEmployee(pm);
		//deleteEmployee(pm);
		System.out.println("Autocommit : " + pm.isAutoCommitMode() ); // true
		
		pm.getTransaction().begin(); // Begin a new transaction

		System.out.println("Autocommit : " + pm.isAutoCommitMode() ); // false
		
		// 3) Use the PersistenceManager
		Employee employee = new Employee();
		employee.setCode("A99");
		if ( pm.load(employee) ) {
			System.out.println("Employee found : " + employee.getFirstName() + " "+ employee.getLastName() );
			String email = employee.getFirstName() + "." + employee.getLastName() + "@mycompany.com" ;
			employee.setEmail(email);
			pm.update(employee);
		}
		else {
			System.out.println("Employee " + employee.getCode() + " not found." );
		}

		pm.getTransaction().commit(); // Commit the current transaction
		
		//pm.getTransaction().rollback(); // Rollback the current transaction
		System.out.println("Autocommit : " + pm.isAutoCommitMode() ); // true

		
		
		if ( pm.load(employee) ) {
			System.out.println("Employee : " + employee );
		}
		
		// 4) Close the PersistenceManager
		pm.close();		
		// No need to close the factory
	}

	private static void createEmployee(PersistenceManager pm ) {
		Employee employee = new Employee();
		employee.setCode("A99");
		employee.setFirstName("John");
		employee.setLastName("Wayne");
		employee.setShopCode("AAA");
		pm.save(employee);
	}
	
	private static void deleteEmployee(PersistenceManager pm ) {
		Employee employee = new Employee();
		employee.setCode("A12");
		pm.delete(employee);
	}
}
